package com.ambercrm.business.webview;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.WebSettings;

import com.ambercrm.R;
import com.ambercrm.base.BaseTitleActivity;
import com.ambercrm.business.location.SelectLocationActivity;
import com.ambercrm.constant.Constant;
import com.ambercrm.tools.LogUtils;
import com.ambercrm.tools.VibrateHelper;
import com.ambercrm.tools.player.Player;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.tencent.smtt.sdk.WebView;

public class WebViewActivity extends BaseTitleActivity {

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_web_view;
    }

    BridgeWebView mWebView; // webview
    String mUrl; // 传进来的URL
    Handler mHandler;
    @Override
    protected void initContentView(View v) {
        mTitleLayout.setVisibility(View.GONE);
        mHandler = new Handler();
        Bundle b = getBundle();
        mUrl = b.getString("url");

        mWebView = v.findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setAllowContentAccess(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.requestFocus();
//        mWebView.getSettings().setSupportZoom(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.setWebContentsDebuggingEnabled(true);
        }
        mWebView.setWebViewClient(new MyWebViewClient(mWebView));
        try {
            registerJsMethod();
            mWebView.loadUrl(mUrl);
        }
        catch (Exception e) {

        }
    }

    public class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    javaCallJs();
                }
            }, 500);

            LogUtils.showLog("onPageFish()");
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            LogUtils.showLog("onReceivedError()");
        }
    }

    // 给web端注册方法，供他调用
    private void registerJsMethod() {
        mWebView.registerHandler("getToken", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                function.onCallBack(sp.getValue(Constant.sp_Token));
            }
        });
    }

    // Java掉js代码
    private void javaCallJs() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mWebView.clearCache(true);
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.stopLoading();
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        } catch (Exception e) {

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
        mWebView.resumeTimers();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.pauseTimers();
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        }
        else {
            finishActivity();
        }
    }

    // 给h5封装方法
    // 拨打电话
    private void callPhone(String phone) {
        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + phone));
        //开启系统拨号器
        startActivity(intent);
    }

    // 选取位置
    private void getLocation() {
        startActivity(SelectLocationActivity.class, null, false);
    }

    // 播放mp3
    private void playMp3() {
        Player player = new Player(this);
        player.playFileDescriptor("");
    }

    // 手机震动
    private void vibrate() {
        VibrateHelper.vibrate(this, new long[] {500, 500, 500}, false);
    }

    private void saveToClipBoard(String str) {
        saveToClipboard(str);
    }
}